<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI驱动的迷你本地PLC控制系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        warning: '#F59E0B',
                        danger: '#EF4444',
                        dark: '#1F2937'
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-shadow {
                box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            }
            .status-indicator {
                width: 12px;
                height: 12px;
                border-radius: 50%;
                display: inline-block;
            }
            .sensor-card {
                transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
            }
            .sensor-card:hover {
                transform: translateY(-2px);
                box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-inter text-dark min-h-screen">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-sm sticky top-0 z-50">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-microchip text-primary text-2xl"></i>
                <h1 class="text-xl font-bold text-primary">AI驱动的迷你本地PLC控制系统</h1>
            </div>
            <div class="flex items-center space-x-4">
                <div class="flex items-center space-x-2">
                    <span id="connection-status-indicator" class="status-indicator bg-gray-300"></span>
                    <span id="connection-status-text" class="text-sm text-gray-500">未连接</span>
                </div>
                <div class="text-sm text-gray-500">
                    <span id="current-time">加载中...</span>
                </div>
            </div>
        </div>
    </header>

    <!-- 主内容区域 -->
    <main class="container mx-auto px-4 py-6">
        <!-- 概览卡片 -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
            <div class="bg-white rounded-lg p-4 card-shadow">
                <div class="flex justify-between items-center mb-2">
                    <h3 class="text-gray-500 text-sm font-medium">最后更新时间</h3>
                    <i class="fa fa-clock-o text-primary"></i>
                </div>
                <p id="last-update-time" class="text-xl font-bold">--:--:--</p>
            </div>
            <div class="bg-white rounded-lg p-4 card-shadow">
                <div class="flex justify-between items-center mb-2">
                    <h3 class="text-gray-500 text-sm font-medium">传感器读数</h3>
                    <i class="fa fa-thermometer-half text-primary"></i>
                </div>
                <p id="sensor-summary" class="text-xl font-bold">0/0/0/0</p>
            </div>
            <div class="bg-white rounded-lg p-4 card-shadow">
                <div class="flex justify-between items-center mb-2">
                    <h3 class="text-gray-500 text-sm font-medium">继电器状态</h3>
                    <i class="fa fa-plug text-primary"></i>
                </div>
                <div id="relay-summary" class="flex space-x-2">
                    <span class="status-indicator bg-gray-300"></span>
                    <span class="status-indicator bg-gray-300"></span>
                    <span class="status-indicator bg-gray-300"></span>
                    <span class="status-indicator bg-gray-300"></span>
                </div>
            </div>
            <div class="bg-white rounded-lg p-4 card-shadow">
                <div class="flex justify-between items-center mb-2">
                    <h3 class="text-gray-500 text-sm font-medium">故障检测</h3>
                    <i id="fault-icon" class="fa fa-check-circle text-gray-300"></i>
                </div>
                <p id="fault-status" class="text-xl font-bold">正常</p>
            </div>
        </div>

        <!-- 图表和控制面板 -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
            <!-- 传感器数据图表 -->
            <div class="bg-white rounded-lg p-4 card-shadow lg:col-span-2">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-lg font-semibold">传感器数据趋势</h2>
                    <div class="flex space-x-2">
                        <button class="chart-time-filter px-3 py-1 text-sm rounded bg-primary text-white" data-range="5m">5分钟</button>
                        <button class="chart-time-filter px-3 py-1 text-sm rounded bg-gray-200 text-gray-700" data-range="1h">1小时</button>
                        <button class="chart-time-filter px-3 py-1 text-sm rounded bg-gray-200 text-gray-700" data-range="24h">24小时</button>
                    </div>
                </div>
                <div class="h-80">
                    <canvas id="sensor-chart"></canvas>
                </div>
            </div>

            <!-- 继电器控制面板 -->
            <div class="bg-white rounded-lg p-4 card-shadow">
                <h2 class="text-lg font-semibold mb-4">继电器控制</h2>
                <div class="space-y-4">
                    <div class="flex items-center justify-between p-3 border rounded-lg bg-gray-50">
                        <div class="flex items-center space-x-3">
                            <i class="fa fa-plug text-primary"></i>
                            <span>继电器 1</span>
                        </div>
                        <label class="relative inline-flex items-center cursor-pointer relay-toggle">
                            <input type="checkbox" class="sr-only peer" data-relay-id="1">
                            <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-secondary"></div>
                        </label>
                    </div>
                    <div class="flex items-center justify-between p-3 border rounded-lg bg-gray-50">
                        <div class="flex items-center space-x-3">
                            <i class="fa fa-plug text-primary"></i>
                            <span>继电器 2</span>
                        </div>
                        <label class="relative inline-flex items-center cursor-pointer relay-toggle">
                            <input type="checkbox" class="sr-only peer" data-relay-id="2">
                            <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-secondary"></div>
                        </label>
                    </div>
                    <div class="flex items-center justify-between p-3 border rounded-lg bg-gray-50">
                        <div class="flex items-center space-x-3">
                            <i class="fa fa-plug text-primary"></i>
                            <span>继电器 3</span>
                        </div>
                        <label class="relative inline-flex items-center cursor-pointer relay-toggle">
                            <input type="checkbox" class="sr-only peer" data-relay-id="3">
                            <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-secondary"></div>
                        </label>
                    </div>
                    <div class="flex items-center justify-between p-3 border rounded-lg bg-gray-50">
                        <div class="flex items-center space-x-3">
                            <i class="fa fa-plug text-primary"></i>
                            <span>继电器 4</span>
                        </div>
                        <label class="relative inline-flex items-center cursor-pointer relay-toggle">
                            <input type="checkbox" class="sr-only peer" data-relay-id="4">
                            <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-secondary"></div>
                        </label>
                    </div>
                </div>
            </div>
        </div>

        <!-- 详细数据和配置 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- 传感器详细数据 -->
            <div class="bg-white rounded-lg p-4 card-shadow">
                <h2 class="text-lg font-semibold mb-4">传感器详细数据</h2>
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div class="sensor-card bg-white p-4 rounded-lg border border-gray-200">
                        <div class="flex justify-between items-start mb-2">
                            <h3 class="text-gray-500 text-sm font-medium">传感器 1</h3>
                            <i class="fa fa-thermometer-half text-primary"></i>
                        </div>
                        <div class="flex items-end space-x-2">
                            <p id="sensor1-value" class="text-3xl font-bold">--</p>
                            <p class="text-gray-500 mb-1">°C</p>
                        </div>
                        <div class="mt-2 text-xs text-gray-500">
                            <span id="sensor1-status" class="px-2 py-1 rounded-full bg-gray-100">稳定</span>
                        </div>
                    </div>
                    <div class="sensor-card bg-white p-4 rounded-lg border border-gray-200">
                        <div class="flex justify-between items-start mb-2">
                            <h3 class="text-gray-500 text-sm font-medium">传感器 2</h3>
                            <i class="fa fa-tint text-primary"></i>
                        </div>
                        <div class="flex items-end space-x-2">
                            <p id="sensor2-value" class="text-3xl font-bold">--</p>
                            <p class="text-gray-500 mb-1">%</p>
                        </div>
                        <div class="mt-2 text-xs text-gray-500">
                            <span id="sensor2-status" class="px-2 py-1 rounded-full bg-gray-100">稳定</span>
                        </div>
                    </div>
                    <div class="sensor-card bg-white p-4 rounded-lg border border-gray-200">
                        <div class="flex justify-between items-start mb-2">
                            <h3 class="text-gray-500 text-sm font-medium">传感器 3</h3>
                            <i class="fa fa-bolt text-primary"></i>
                        </div>
                        <div class="flex items-end space-x-2">
                            <p id="sensor3-value" class="text-3xl font-bold">--</p>
                            <p class="text-gray-500 mb-1">V</p>
                        </div>
                        <div class="mt-2 text-xs text-gray-500">
                            <span id="sensor3-status" class="px-2 py-1 rounded-full bg-gray-100">稳定</span>
                        </div>
                    </div>
                    <div class="sensor-card bg-white p-4 rounded-lg border border-gray-200">
                        <div class="flex justify-between items-start mb-2">
                            <h3 class="text-gray-500 text-sm font-medium">传感器 4</h3>
                            <i class="fa fa-leaf text-primary"></i>
                        </div>
                        <div class="flex items-end space-x-2">
                            <p id="sensor4-value" class="text-3xl font-bold">--</p>
                            <p class="text-gray-500 mb-1">PPM</p>
                        </div>
                        <div class="mt-2 text-xs text-gray-500">
                            <span id="sensor4-status" class="px-2 py-1 rounded-full bg-gray-100">稳定</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 系统配置 -->
            <div class="bg-white rounded-lg p-4 card-shadow">
                <h2 class="text-lg font-semibold mb-4">系统配置</h2>
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">串行端口</label>
                        <div class="flex space-x-2">
                            <input type="text" id="serial-port" class="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary" placeholder="COM3">
                            <button id="save-serial-port" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors">保存</button>
                        </div>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">波特率</label>
                        <div class="flex space-x-2">
                            <select id="baud-rate" class="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary">
                                <option value="9600">9600</option>
                                <option value="19200">19200</option>
                                <option value="38400">38400</option>
                                <option value="57600">57600</option>
                                <option value="115200">115200</option>
                            </select>
                            <button id="save-baud-rate" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors">保存</button>
                        </div>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">数据刷新频率 (秒)</label>
                        <div class="flex space-x-2">
                            <input type="number" id="refresh-rate" min="1" max="60" class="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary" value="1">
                            <button id="save-refresh-rate" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors">保存</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-white border-t mt-8 py-6">
        <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
            <p>&copy; 2025 AI驱动的迷你本地PLC控制系统 - 小而美，智能化</p>
            <p class="mt-1">本系统采用Arduino + Python Flask + SQLite技术栈，结合AI故障检测功能</p>
        </div>
    </footer>

    <!-- JavaScript -->
    <script>
        // 全局变量
        let sensorChart = null;
        let refreshInterval = 1000; // 默认1秒刷新一次
        let refreshTimer = null;

        // 初始化图表
        function initChart() {
            const ctx = document.getElementById('sensor-chart').getContext('2d');
            sensorChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: Array(30).fill(''),
                    datasets: [
                        {
                            label: '传感器1 (°C)',
                            data: Array(30).fill(null),
                            borderColor: '#3B82F6',
                            backgroundColor: 'rgba(59, 130, 246, 0.1)',
                            borderWidth: 2,
                            tension: 0.4,
                            fill: false
                        },
                        {
                            label: '传感器2 (%)',
                            data: Array(30).fill(null),
                            borderColor: '#10B981',
                            backgroundColor: 'rgba(16, 185, 129, 0.1)',
                            borderWidth: 2,
                            tension: 0.4,
                            fill: false
                        },
                        {
                            label: '传感器3 (V)',
                            data: Array(30).fill(null),
                            borderColor: '#F59E0B',
                            backgroundColor: 'rgba(245, 158, 11, 0.1)',
                            borderWidth: 2,
                            tension: 0.4,
                            fill: false
                        },
                        {
                            label: '传感器4 (PPM)',
                            data: Array(30).fill(null),
                            borderColor: '#EF4444',
                            backgroundColor: 'rgba(239, 68, 68, 0.1)',
                            borderWidth: 2,
                            tension: 0.4,
                            fill: false
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'top',
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                        }
                    },
                    scales: {
                        x: {
                            display: true,
                            title: {
                                display: true,
                                text: '时间'
                            }
                        },
                        y: {
                            display: true,
                            title: {
                                display: true,
                                text: '数值'
                            },
                            beginAtZero: false
                        }
                    },
                    interaction: {
                        intersect: false,
                        mode: 'index',
                    },
                    animation: {
                        duration: 0
                    }
                }
            });
        }

        // 更新图表数据
        function updateChart(data) {
            if (sensorChart) {
                const now = new Date();
                const timeStr = now.getHours() + ':' + (now.getMinutes() < 10 ? '0' : '') + now.getMinutes() + ':' + (now.getSeconds() < 10 ? '0' : '') + now.getSeconds();
                
                // 删除最早的数据点
                sensorChart.data.labels.shift();
                sensorChart.data.datasets.forEach(dataset => dataset.data.shift());
                
                // 添加新的数据点
                sensorChart.data.labels.push(timeStr);
                
                // 假设data中包含sensor1, sensor2, sensor3, sensor4的值
                sensorChart.data.datasets[0].data.push(data.sensor1 || null);
                sensorChart.data.datasets[1].data.push(data.sensor2 || null);
                sensorChart.data.datasets[2].data.push(data.sensor3 || null);
                sensorChart.data.datasets[3].data.push(data.sensor4 || null);
                
                // 更新图表
                sensorChart.update();
            }
        }

        // 获取最新数据
        function getLatestData() {
            fetch('/api/latest_data')
                .then(response => response.json())
                .then(data => {
                    if (Object.keys(data).length > 0) {
                        updateUI(data);
                        updateChart(data);
                        updateConnectionStatus(true);
                    } else {
                        updateConnectionStatus(false);
                    }
                })
                .catch(error => {
                    console.error('Error fetching data:', error);
                    updateConnectionStatus(false);
                });
        }

        // 更新UI显示
        function updateUI(data) {
            // 更新最后更新时间
            if (data.timestamp) {
                document.getElementById('last-update-time').textContent = data.timestamp;
            }
            
            // 更新传感器摘要
            const sensorSummary = `${data.sensor1 || '--'}/${data.sensor2 || '--'}/${data.sensor3 || '--'}/${data.sensor4 || '--'}`;
            document.getElementById('sensor-summary').textContent = sensorSummary;
            
            // 更新继电器摘要
            const relayIndicators = document.getElementById('relay-summary').querySelectorAll('.status-indicator');
            for (let i = 0; i < 4; i++) {
                const relayKey = `relay${i + 1}`;
                const state = data[relayKey] || 0;
                relayIndicators[i].className = `status-indicator ${state ? 'bg-secondary' : 'bg-gray-300'}`;
                
                // 更新继电器开关状态
                const toggleInput = document.querySelector(`.relay-toggle input[data-relay-id="${i + 1}"]`);
                if (toggleInput) {
                    // 避免触发change事件
                    toggleInput.checked = state === 1;
                }
            }
            
            // 更新故障状态
            const faultStatus = data.fault_status || 0;
            const faultStatusEl = document.getElementById('fault-status');
            const faultIconEl = document.getElementById('fault-icon');
            
            if (faultStatus === 0) {
                faultStatusEl.textContent = '正常';
                faultStatusEl.className = 'text-xl font-bold text-secondary';
                faultIconEl.className = 'fa fa-check-circle text-secondary';
            } else {
                faultStatusEl.textContent = '异常';
                faultStatusEl.className = 'text-xl font-bold text-danger';
                faultIconEl.className = 'fa fa-exclamation-circle text-danger';
            }
            
            // 更新传感器详细数据
            for (let i = 1; i <= 4; i++) {
                const sensorKey = `sensor${i}`;
                const sensorValue = data[sensorKey] || '--';
                document.getElementById(`${sensorKey}-value`).textContent = sensorValue;
                
                // 简单的状态判断（实际应用中可以根据具体的传感器类型和阈值调整）
                let statusClass = 'bg-gray-100';
                let statusText = '稳定';
                
                if (typeof sensorValue === 'number') {
                    if (i === 1 && (sensorValue < 0 || sensorValue > 100)) {
                        statusClass = 'bg-danger/10 text-danger';
                        statusText = '超范围';
                    } else if (i === 2 && (sensorValue < 0 || sensorValue > 100)) {
                        statusClass = 'bg-danger/10 text-danger';
                        statusText = '超范围';
                    } else if (i === 3 && (sensorValue < 0 || sensorValue > 24)) {
                        statusClass = 'bg-danger/10 text-danger';
                        statusText = '超范围';
                    } else if (i === 4 && (sensorValue < 0 || sensorValue > 2000)) {
                        statusClass = 'bg-danger/10 text-danger';
                        statusText = '超范围';
                    } else if (faultStatus > 0) {
                        statusClass = 'bg-warning/10 text-warning';
                        statusText = '需关注';
                    }
                }
                
                document.getElementById(`${sensorKey}-status`).className = `px-2 py-1 rounded-full ${statusClass}`;
                document.getElementById(`${sensorKey}-status`).textContent = statusText;
            }
        }

        // 更新连接状态
        function updateConnectionStatus(connected) {
            const statusIndicator = document.getElementById('connection-status-indicator');
            const statusText = document.getElementById('connection-status-text');
            
            if (connected) {
                statusIndicator.className = 'status-indicator bg-secondary';
                statusText.textContent = '已连接';
                statusText.className = 'text-sm text-secondary';
            } else {
                statusIndicator.className = 'status-indicator bg-danger';
                statusText.textContent = '未连接';
                statusText.className = 'text-sm text-danger';
            }
        }

        // 更新当前时间
        function updateCurrentTime() {
            const now = new Date();
            const timeStr = now.getFullYear() + '-' + 
                          (now.getMonth() + 1).toString().padStart(2, '0') + '-' + 
                          now.getDate().toString().padStart(2, '0') + ' ' + 
                          now.getHours().toString().padStart(2, '0') + ':' + 
                          now.getMinutes().toString().padStart(2, '0') + ':' + 
                          now.getSeconds().toString().padStart(2, '0');
            document.getElementById('current-time').textContent = timeStr;
        }

        // 控制继电器
        function controlRelay(relayId, state) {
            fetch('/api/control_relay', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    relay_id: relayId,
                    state: state
                })
            })
            .then(response => response.json())
            .then(data => {
                if (!data.success) {
                    console.error('Failed to control relay:', data.message);
                    // 回滚开关状态
                    setTimeout(() => {
                        const toggleInput = document.querySelector(`.relay-toggle input[data-relay-id="${relayId}"]`);
                        if (toggleInput) {
                            toggleInput.checked = !state;
                        }
                    }, 500);
                }
            })
            .catch(error => {
                console.error('Error controlling relay:', error);
                // 回滚开关状态
                setTimeout(() => {
                    const toggleInput = document.querySelector(`.relay-toggle input[data-relay-id="${relayId}"]`);
                    if (toggleInput) {
                        toggleInput.checked = !state;
                    }
                }, 500);
            });
        }

        // 保存配置
        function saveConfig(name, value) {
            fetch('/api/set_config', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    name: name,
                    value: value
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 显示成功提示
                    alert('配置保存成功');
                } else {
                    console.error('Failed to save config:', data.message);
                    alert('配置保存失败');
                }
            })
            .catch(error => {
                console.error('Error saving config:', error);
                alert('配置保存失败');
            });
        }

        // 获取配置
        function loadConfig() {
            fetch('/api/get_config')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const configs = data.configs || {};
                        
                        // 加载串行端口配置
                        if (configs.serial_port) {
                            document.getElementById('serial-port').value = configs.serial_port;
                        }
                        
                        // 加载波特率配置
                        if (configs.baud_rate) {
                            document.getElementById('baud-rate').value = configs.baud_rate;
                        }
                        
                        // 加载刷新频率配置
                        if (configs.refresh_rate) {
                            document.getElementById('refresh-rate').value = configs.refresh_rate;
                            refreshInterval = parseInt(configs.refresh_rate) * 1000;
                            restartRefreshTimer();
                        }
                    }
                })
                .catch(error => {
                    console.error('Error loading config:', error);
                });
        }

        // 开始数据刷新定时器
        function startRefreshTimer() {
            refreshTimer = setInterval(getLatestData, refreshInterval);
        }

        // 重启数据刷新定时器
        function restartRefreshTimer() {
            if (refreshTimer) {
                clearInterval(refreshTimer);
            }
            startRefreshTimer();
        }

        // 初始化页面
        function initPage() {
            // 初始化图表
            initChart();
            
            // 加载配置
            loadConfig();
            
            // 开始数据刷新
            startRefreshTimer();
            
            // 获取初始数据
            getLatestData();
            
            // 设置时间更新
            updateCurrentTime();
            setInterval(updateCurrentTime, 1000);
            
            // 添加继电器控制事件监听
            document.querySelectorAll('.relay-toggle input').forEach(input => {
                input.addEventListener('change', function() {
                    const relayId = parseInt(this.getAttribute('data-relay-id'));
                    const state = this.checked ? 1 : 0;
                    controlRelay(relayId, state);
                });
            });
            
            // 添加配置保存事件监听
            document.getElementById('save-serial-port').addEventListener('click', function() {
                const port = document.getElementById('serial-port').value;
                saveConfig('serial_port', port);
            });
            
            document.getElementById('save-baud-rate').addEventListener('click', function() {
                const baudRate = document.getElementById('baud-rate').value;
                saveConfig('baud_rate', baudRate);
            });
            
            document.getElementById('save-refresh-rate').addEventListener('click', function() {
                const refreshRate = document.getElementById('refresh-rate').value;
                saveConfig('refresh_rate', refreshRate);
            });
            
            // 添加图表时间范围过滤事件监听
            document.querySelectorAll('.chart-time-filter').forEach(button => {
                button.addEventListener('click', function() {
                    // 移除所有按钮的活跃状态
                    document.querySelectorAll('.chart-time-filter').forEach(btn => {
                        btn.className = 'chart-time-filter px-3 py-1 text-sm rounded bg-gray-200 text-gray-700';
                    });
                    
                    // 添加当前按钮的活跃状态
                    this.className = 'chart-time-filter px-3 py-1 text-sm rounded bg-primary text-white';
                    
                    // 这里可以根据需要加载不同时间范围的数据
                    const range = this.getAttribute('data-range');
                    console.log('Loading data for range:', range);
                    // 实际应用中可以在这里重新加载历史数据
                });
            });
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', initPage);
    </script>
</body>
</html>